﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FitProtocolLibrary
{
    public struct FitFileHeader
    {
        public byte HeaderSize;
        public byte ProtocolVersion;
        public byte[] ProfileVersion;
        public byte[] DataSize;
        public byte[] DataType;
        public byte[] Crc;

        public byte[] Header
        {
            get
            {
                byte[] header = new byte[this.HeaderSize];
                header[0] = this.HeaderSize;
                header[1] = this.ProtocolVersion;
                header[2] = this.ProfileVersion[0];
                header[3] = this.ProfileVersion[1];
                header[4] = this.DataSize[0];
                header[5] = this.DataSize[1];
                header[6] = this.DataSize[2];
                header[7] = this.DataSize[3];
                header[8] = this.DataType[0];
                header[9] = this.DataType[1];
                header[10] = this.DataType[2];
                header[11] = this.DataType[3];
                if (this.HeaderSize >= 14)
                {
                    header[12] = this.Crc[0];
                    header[13] = this.Crc[1];
                }
                return header;
            }
        }

        public FitFileHeader(byte[] header)
        {
            if (header.Length < 12)
                throw new ArgumentOutOfRangeException("header", "File header must be at least 12 bytes long.");

            this.HeaderSize = header[0];
            
            this.ProtocolVersion = header[1];

            this.ProfileVersion = new byte[2];
            this.ProfileVersion[0] = header[2];
            this.ProfileVersion[1] = header[3];

            this.DataSize = new byte[4];
            this.DataSize[0] = header[4];
            this.DataSize[1] = header[5];
            this.DataSize[2] = header[6];
            this.DataSize[3] = header[7];

            this.DataType = new byte[4];
            this.DataType[0] = header[8];
            this.DataType[1] = header[9];
            this.DataType[2] = header[10];
            this.DataType[3] = header[11];

            this.Crc = new byte[2];
            if (header.Length >= 14)
            {
                this.Crc[0] = header[12];
                this.Crc[1] = header[13];
            }
        }
    }
}
